# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _

from .check_zncspt import access_token_check
import datetime

import logging

_logger = logging.getLogger(__name__)


class CompanyConfig(models.Model):
    _name = "fp.company.zncspt"
    _inherit = ['fp.company.config.mixin']
    _description = "Fapiao Company zncspt"
    _order = 'name'

    check_provider_id = fields.Many2one(
        'fp.check.provider',
        string='Check Provider',
        compute='_compute_check_provider_id')

    @api.depends('company_id')
    def _compute_check_provider_id(self):
        for one in self:
            company_api_provider = self.env[
                'fp.company.api.provider'].search_by_company(one.company_id)
            one.check_provider_id = company_api_provider.check_provider_id

    access_token = fields.Char(string='Access Token')
    expires_in = fields.Integer(string='Expires_in')
    lasttime = fields.Datetime(string='Lasttime')

    def access_token_check(self):
        res = access_token_check(self)
        _logger.info("Nuonuo Token is checked: %s" % res)

        if res:
            now = datetime.datetime.now()
            self.write({
                'access_token': res['access_token'],
                'expires_in': res['expires_in'],
                'lasttime': now.strftime('%Y-%m-%d %H:%M:%S'),
            })

        return res
